package com.newer.his.common.util;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
import org.springframework.security.crypto.password.PasswordEncoder;

// 安全组件
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
	
	// 容器注入一个数据源
	@Autowired
	DataSource datasource;

	// 认证
	@Override
	protected void configure(AuthenticationManagerBuilder auth) throws Exception {

		PasswordEncoder encoder;

		// 从工厂获取一个
		encoder = PasswordEncoderFactories.createDelegatingPasswordEncoder();
		
		// 基于 JDBC 的用户认证
		// 1）设置密码的加密方案
		// 2）设置数据源，连接哪一个数据库
		// 3）根据用户名查询用户信息（登陆认证）
		// 4）根据用户名查询角色（授权）
		auth.jdbcAuthentication()
			.passwordEncoder(encoder)
			.dataSource(datasource)
			.usersByUsernameQuery("select username,password,enabled from users where username = ?")
			.authoritiesByUsernameQuery("select username,auth from auths where username = ?");
	}
	
	// 授权
	@Override
	protected void configure(HttpSecurity http) throws Exception {
		
		// post 跨站请求伪造
		http.csrf().disable();
		
		http.authorizeRequests()
			.antMatchers("/","/about","/pw","/zhuce","/po").permitAll()
			.antMatchers("/user","/user/*").hasAnyRole("USER")
			.antMatchers("/vip","/vip/*").hasAnyRole("VIP")
			.antMatchers("/admin","/admin/*").hasRole("ADMIN")
			.and().formLogin()
			.and().httpBasic();
	}
}
